<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品详情 - 商品评价系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .product-image {
            max-width: 100%;
            height: 400px;
            object-fit: cover;
            border-radius: 10px;
        }
        .rating {
            color: #ffc107;
        }
        .rating-large {
            font-size: 1.5rem;
        }
        .price {
            font-size: 2rem;
            font-weight: bold;
            color: #e74c3c;
        }
        .review-card {
            border: none;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .review-rating {
            color: #ffc107;
        }
        .review-content {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin: 10px 0;
        }
        .rating-summary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 10px;
            padding: 20px;
        }
        .rating-bar {
            background: rgba(255,255,255,0.3);
            height: 8px;
            border-radius: 4px;
            overflow: hidden;
        }
        .rating-fill {
            background: #ffc107;
            height: 100%;
            transition: width 0.3s;
        }
        .btn-review {
            background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
        }
        .btn-review:hover {
            background: linear-gradient(45deg, #5a6fd8 0%, #6a4190 100%);
            color: white;
        }
        .star-rating {
            font-size: 1.5rem;
            color: #ddd;
            cursor: pointer;
        }
        .star-rating.active {
            color: #ffc107;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <div class="container">
            <a class="navbar-brand" href="/product-review/page/index">
                <i class="fas fa-shopping-cart me-2"></i>商品评价系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/product-review/page/index">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/product-review/page/products">商品列表</a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item" id="loginNav">
                        <a class="nav-link" href="/product-review/page/login">登录</a>
                    </li>
                    <li class="nav-item" id="registerNav">
                        <a class="nav-link" href="/product-review/page/register">注册</a>
                    </li>
                    <li class="nav-item dropdown" id="userNav" style="display: none;">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="username"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/product-review/page/user-center">个人中心</a></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 面包屑导航 -->
    <div class="container mt-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="/product-review/page/index">首页</a></li>
                <li class="breadcrumb-item"><a href="/product-review/page/products">商品列表</a></li>
                <li class="breadcrumb-item active" aria-current="page" id="breadcrumbProduct">商品详情</li>
            </ol>
        </nav>
    </div>

    <!-- 商品详情 -->
    <div class="container my-4">
        <div class="row" id="productDetail">
            <!-- 商品信息将通过JavaScript动态加载 -->
        </div>
    </div>

    <!-- 评价统计 -->
    <div class="container my-5">
        <div class="row">
            <div class="col-lg-4">
                <div class="rating-summary text-center">
                    <h3>用户评价</h3>
                    <div class="rating-large mb-3" id="averageRating">
                        <span id="avgScore">0.0</span>
                        <div id="avgStars"></div>
                    </div>
                    <p class="mb-0">基于 <span id="totalReviews">0</span> 条评价</p>
                </div>
                
                <div class="mt-4" id="ratingBreakdown">
                    <!-- 评分分布将通过JavaScript动态加载 -->
                </div>
            </div>
            
            <div class="col-lg-8">
                <!-- 写评价按钮 -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h4>用户评价</h4>
                    <button class="btn btn-review" id="writeReviewBtn" onclick="showReviewModal()">
                        <i class="fas fa-edit me-2"></i>写评价
                    </button>
                </div>
                
                <!-- 评价筛选 -->
                <div class="mb-4">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary active" onclick="filterReviews('all', this)">全部</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterReviews(5, this)">5星</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterReviews(4, this)">4星</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterReviews(3, this)">3星</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterReviews(2, this)">2星</button>
                        <button type="button" class="btn btn-outline-primary" onclick="filterReviews(1, this)">1星</button>
                    </div>
                </div>
                
                <!-- 评价列表 -->
                <div id="reviewsList">
                    <!-- 评价列表将通过JavaScript动态加载 -->
                </div>
                
                <!-- 加载更多 -->
                <div class="text-center mt-4">
                    <button class="btn btn-outline-primary" id="loadMoreBtn" onclick="loadMoreReviews()" style="display: none;">
                        加载更多评价
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 写评价模态框 -->
    <div class="modal fade" id="reviewModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">写评价</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="reviewForm">
                        <div class="mb-3">
                            <label class="form-label">评分</label>
                            <div class="star-rating-input">
                                <i class="fas fa-star star-rating" data-rating="1"></i>
                                <i class="fas fa-star star-rating" data-rating="2"></i>
                                <i class="fas fa-star star-rating" data-rating="3"></i>
                                <i class="fas fa-star star-rating" data-rating="4"></i>
                                <i class="fas fa-star star-rating" data-rating="5"></i>
                            </div>
                            <input type="hidden" id="rating" name="rating" value="5">
                        </div>
                        <div class="mb-3">
                            <label for="reviewContent" class="form-label">评价内容</label>
                            <textarea class="form-control" id="reviewContent" name="content" rows="4" 
                                      placeholder="请分享您的使用体验..." required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitReview()">提交评价</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="bg-dark text-light py-4 mt-5">
        <div class="container">
            <div class="text-center">
                <p>&copy; 2024 商品评价系统. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // 全局变量
        let productId = null;
        let currentUser = null;
        let reviewPage = 1;
        let reviewFilter = 'all';
        let reviewModal = null;
        
        $(document).ready(function() {
            // 获取商品ID
            const urlParams = new URLSearchParams(window.location.search);
            productId = urlParams.get('id');
            
            if (!productId) {
                alert('商品ID不存在');
                window.location.href = '/product-review/page/products';
                return;
            }
            
            // 初始化模态框
            reviewModal = new bootstrap.Modal(document.getElementById('reviewModal'));
            
            // 检查登录状态
            checkLoginStatus();
            
            // 加载商品详情
            loadProductDetail();
            
            // 加载评价统计
            loadReviewStats();
            
            // 加载评价列表
            loadReviews();
            
            // 初始化星级评分
            initStarRating();
        });
        
        // 检查登录状态
        function checkLoginStatus() {
            $.ajax({
                url: '/product-review/user/current',
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        currentUser = result.data;
                        $('#loginNav, #registerNav').hide();
                        $('#userNav').show();
                        $('#username').text(result.data.username);
                    } else {
                        currentUser = null;
                        $('#loginNav, #registerNav').show();
                        $('#userNav').hide();
                    }
                },
                error: function() {
                    currentUser = null;
                    $('#loginNav, #registerNav').show();
                    $('#userNav').hide();
                }
            });
        }
        
        // 加载商品详情
        function loadProductDetail() {
            $.ajax({
                url: `/product-review/product/\${productId}`,
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        displayProductDetail(result.data);
                    } else {
                        alert('商品不存在');
                        window.location.href = '/product-review/page/products';
                    }
                },
                error: function() {
                    alert('加载商品详情失败');
                    window.location.href = '/product-review/page/products';
                }
            });
        }
        
        // 显示商品详情
        function displayProductDetail(product) {
            $('#breadcrumbProduct').text(product.name);
            
            const html = `
                <div class="col-lg-6">
                    <img src="\${product.imageUrl || '/product-review/static/img/default-product.jpg'}"
                         class="product-image" alt="\${product.name}">
                </div>
                <div class="col-lg-6">
                    <h1 class="mb-3">\${product.name}</h1>
                    <div class="rating mb-3">
                        <span id="productRating"></span>
                        <small class="text-muted ms-2">(<span id="productReviewCount">0</span> 条评价)</small>
                    </div>
                    <div class="price mb-4">¥\${product.price}</div>
                    <div class="mb-4">
                        <h5>商品描述</h5>
                        <p class="text-muted">\${product.description || '暂无描述'}</p>
                    </div>
                    <div class="mb-4">
                        <div class="row">
                            <div class="col-6">
                                <strong>分类：</strong>\${product.category || '未分类'}
                            </div>
                            <div class="col-6">
                                <strong>库存：</strong>\${product.stock || 0} 件
                            </div>
                        </div>
                    </div>
                    <div class="d-flex gap-3">
                        <button class="btn btn-primary btn-lg flex-grow-1" onclick="addToCart()">
                            <i class="fas fa-shopping-cart me-2"></i>加入购物车
                        </button>
                        <button class="btn btn-outline-primary btn-lg" onclick="addToFavorites()">
                            <i class="fas fa-heart"></i>
                        </button>
                    </div>
                </div>
            `;
            
            $('#productDetail').html(html);
        }
        
        // 加载评价统计
        function loadReviewStats() {
            $.ajax({
                url: `/product-review/review/stats/\${productId}`,
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        displayReviewStats(result.data);
                    }
                }
            });
        }
        
        // 显示评价统计
        function displayReviewStats(stats) {
            const avgRating = stats.averageRating || 0;
            const totalReviews = stats.total || 0;
            
            $('#avgScore').text(avgRating.toFixed(1));
            $('#totalReviews').text(totalReviews);
            $('#productReviewCount').text(totalReviews);
            
            // 显示平均评分星级
            let starsHtml = '';
            for (let i = 1; i <= 5; i++) {
                if (i <= avgRating) {
                    starsHtml += '<i class="fas fa-star"></i>';
                } else if (i - 0.5 <= avgRating) {
                    starsHtml += '<i class="fas fa-star-half-alt"></i>';
                } else {
                    starsHtml += '<i class="far fa-star"></i>';
                }
            }
            $('#avgStars').html(starsHtml);
            $('#productRating').html(starsHtml);
            
            // 显示评分分布
            if (stats.ratingStats) {
                let breakdownHtml = '';
                for (let i = 5; i >= 1; i--) {
                    const count = stats.ratingStats[i] || 0;
                    const percentage = totalReviews > 0 ? (count / totalReviews * 100) : 0;
                    
                    breakdownHtml += `
                        <div class="d-flex align-items-center mb-2">
                            <span class="me-2">\${i}星</span>
                            <div class="rating-bar flex-grow-1 me-2">
                                <div class="rating-fill" style="width: \${percentage}%"></div>
                            </div>
                            <span class="text-muted">\${count}</span>
                        </div>
                    `;
                }
                $('#ratingBreakdown').html(breakdownHtml);
            }
        }
        
        // 加载评价列表
        function loadReviews() {
            const params = {
                page: reviewPage,
                size: 10
            };
            
            if (reviewFilter !== 'all') {
                params.rating = reviewFilter;
            }
            
            $.ajax({
                url: `/product-review/review/product/\${productId}`,
                type: 'GET',
                data: params,
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        const reviews = result.data.list || [];
                        displayReviews(reviews, reviewPage === 1);
                        
                        // 检查是否还有更多评价
                        if (reviews.length === result.data.size && result.data.page < result.data.pages) {
                            $('#loadMoreBtn').show();
                        } else {
                            $('#loadMoreBtn').hide();
                        }
                    }
                }
            });
        }
        
        // 显示评价列表
        function displayReviews(reviews, replace = false) {
            if (reviews.length === 0 && replace) {
                $('#reviewsList').html('<div class="text-center text-muted py-5"><i class="fas fa-comments fa-3x mb-3"></i><p>暂无评价</p></div>');
                return;
            }
            
            let html = '';
            reviews.forEach(function(review) {
                html += createReviewCard(review);
            });
            
            if (replace) {
                $('#reviewsList').html(html);
            } else {
                $('#reviewsList').append(html);
            }
        }
        
        // 创建评价卡片
        function createReviewCard(review) {
            const stars = generateStars(review.rating);
            const createTime = new Date(review.createTime).toLocaleDateString();
            
            return `
                <div class="review-card card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div>
                                <strong>\${review.username || '匿名用户'}</strong>
                                <div class="review-rating">\${stars}</div>
                            </div>
                            <small class="text-muted">\${createTime}</small>
                        </div>
                        <div class="review-content">
                            \${review.content || '用户没有留下评价内容'}
                        </div>
                    </div>
                </div>
            `;
        }
        
        // 生成星级显示
        function generateStars(rating) {
            let html = '';
            for (let i = 1; i <= 5; i++) {
                if (i <= rating) {
                    html += '<i class="fas fa-star"></i>';
                } else {
                    html += '<i class="far fa-star"></i>';
                }
            }
            return html;
        }
        
        // 筛选评价
        function filterReviews(rating, element) {
            reviewFilter = rating;
            reviewPage = 1;
            
            // 更新按钮状态
            $('.btn-group button').removeClass('active');
            if (element) {
                element.classList.add('active');
            } else {
                $(`.btn-group button[onclick*="'${rating}'"]").addClass('active'`);
            }
            
            loadReviews();
        }
        
        // 加载更多评价
        function loadMoreReviews() {
            reviewPage++;
            loadReviews();
        }
        
        // 显示写评价模态框
        function showReviewModal() {
            if (!currentUser) {
                if (confirm('请先登录后再评价，是否前往登录？')) {
                    window.location.href = '/product-review/page/login';
                }
                return;
            }
            
            // 检查是否已经评价过
            $.ajax({
                url: `/product-review/review/check/\${productId}`,
                type: 'GET',
                success: function(result) {
                    if (result.code === 200 && result.data) {
                        alert('您已经评价过这个商品了');
                    } else {
                        reviewModal.show();
                    }
                },
                error: function() {
                    reviewModal.show();
                }
            });
        }
        
        // 初始化星级评分
        function initStarRating() {
            $('.star-rating').click(function() {
                const rating = $(this).data('rating');
                $('#rating').val(rating);
                
                $('.star-rating').removeClass('active');
                for (let i = 1; i <= rating; i++) {
                    $(`.star-rating[data-rating="\${i}"]`).addClass('active');
                }
            });
            
            // 默认选中5星
            $('.star-rating').addClass('active');
        }
        
        // 提交评价
        function submitReview() {
            const rating = $('#rating').val();
            const content = $('#reviewContent').val().trim();
            
            if (!content) {
                alert('请输入评价内容');
                return;
            }
            
            const reviewData = {
                productId: parseInt(productId),
                rating: parseInt(rating),
                content: content
            };
            
            $.ajax({
                url: '/product-review/review/add',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(reviewData),
                success: function(result) {
                    if (result.code === 200) {
                        alert('评价提交成功');
                        reviewModal.hide();
                        
                        // 重置表单
                        $('#reviewContent').val('');
                        $('#rating').val('5');
                        $('.star-rating').addClass('active');
                        
                        // 重新加载评价
                        reviewPage = 1;
                        loadReviews();
                        loadReviewStats();
                    } else {
                        alert('评价提交失败：' + result.message);
                    }
                },
                error: function() {
                    alert('评价提交失败');
                }
            });
        }
        
        // 加入购物车
        function addToCart() {
            if (!currentUser) {
                if (confirm('请先登录后再加入购物车，是否前往登录？')) {
                    window.location.href = '/product-review/page/login';
                }
                return;
            }
            
            alert('购物车功能待完善');
        }
        
        // 添加到收藏
        function addToFavorites() {
            if (!currentUser) {
                if (confirm('请先登录后再收藏商品，是否前往登录？')) {
                    window.location.href = '/product-review/page/login';
                }
                return;
            }
            
            alert('收藏功能待完善');
        }
        
        // 退出登录
        function logout() {
            $.ajax({
                url: '/product-review/user/logout',
                type: 'POST',
                success: function(result) {
                    if (result.code === 200) {
                        location.reload();
                    } else {
                        alert('退出登录失败：' + result.message);
                    }
                },
                error: function() {
                    alert('退出登录失败');
                }
            });
        }
    </script>
</body>
</html>